<?php
/*
 * Created on Apr 15, 2012
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
include_once("model/Model.php");
include_once("model/Player.php");
include_once("model/Event.php");
include_once("model/Venue.php");
require_once("model/ImportStatus.php");
include_once("model/AdminItemEnum.php");
 
 class Controller {
 	
 	public $model;
 	public $appRoot;
 	
 	public function __construct(){
 		$this->model = Model::getInstance();
 		$httpHost = strtolower($_SERVER["HTTP_HOST"]);
		$virDir = $_SERVER['DOCUMENT_ROOT'];
		$virDir .= ($httpHost=="localhost")?"/wjci":"";
		$this->appRoot = $virDir;
 	}
 	
 	public function invoke(){
 		
 		if(isset($_GET["dosoap"]) || isset($_POST["dosoap"])){
 			//Uploading image
 			if(isset($_GET["upload"])){
 				$jsonOutput = "";
 				include_once("modules/mod_upload_image.php");
 				include_once("soap/UploadImage.php");
 			}
 			else if(isset($_GET["uploadVenuePic"])){
 				header("Content-type: application/json");
 				include_once("components/func.php");
 				$this->model->updateVenuePhoto($_POST["hdnVenueId"],uploadImg($_FILES,"newImage"));
 			}
 			//Set profile picture
 			else if(isset($_POST["saveProf"]) || isset($_GET["saveProf"])){
 				header("Content-type: application/json");
 				
 				try{
 					if(isset($_POST["photo_id"]))
 						$this->model->setProfilePic($_POST["playerid"],$_POST["photo_id"]);
 				
 					if(isset($_POST["photos2del"]) && $_POST["photos2del"] != ""){
 						$this->model->deletePhotos($_POST["photos2del"]);
 					}
 				}
 				catch(Exception $ex){
 					printf("{\"error\":\"%s\"}",$ex->getMessage());
 				}	
 			}
 			//display uploaded photos
 			else if(isset($_GET["listProfPics"])){
 				header("Content-type: application/json");
 				$results = $this->model->getPhotosByPlayerId($_POST["playerid"]);
 				include_once("soap/ListProfilePictures.php");
 			}
 			exit();
 		}
 		
 		if(isset($_GET["display"]) && isset($_GET["photo_id"]) && isset($_GET["size"])){
 			$photo = $this->model->getPhoto($_GET["photo_id"]);
 			include_once("components/display_photo.php");
 			exit();
 		}
 		
 		if(isset($_GET["displayVenuePhoto"]) && isset($_GET["venueid"])){
 			$venuephoto = $this->model->getVenuePhoto($_GET["venueid"]);
 			include_once("components/display_venue_photo.php");
 			exit();
 		}
 			
 		//Logout
 		if(isset($_GET["logout"])){
	 		 session_destroy();
	 		 header("Location:index.php");
 		}
 		
 		//Login
 		if(isset($_POST["emailaddress"]) && isset($_POST["password"])){
 			$me = $this->model->login($_POST["emailaddress"],$_POST["password"]);
 			if($me != null){
 				$_SESSION["me"] = $me;
 				$this->model->isAdmin = $me->admin;
 			}
 			header("Location:index.php");
 		}
 		
 		//Check if the user is authorized administrator
 		$this->model->isAdmin = (isset($_SESSION["me"]))?$_SESSION["me"]->admin:false;

 		//Check if it's in "admin mode"
 		foreach($this->model->listAdminItem as $key=>$val){
 			$this->model->adminMode = false;
 			if(isset($_GET[$key]) || isset($_POST[$key])){
 				$this->model->adminMode = true;
 				break;
 			}
 		}
 		
 		$playerid = -1;
 		
 		if(isset($_POST["playerid"]) && trim($_POST["playerid"]) != "" && is_numeric($_POST["playerid"])){
 			$playerid = $_POST["playerid"]; 
 		}
 		else if(isset($_GET["playerid"]) && trim($_GET["playerid"]) != "" && is_numeric($_GET["playerid"])){
 			$playerid = $_GET["playerid"];
 		}
 		
 		//Saving profile
 		if(isset($_POST["btnSaveProfile"])){
 			
	 		$isEdit = ($playerid != -1);
	 		
	 		$p = ($isEdit)?$this->model->getPlayerById($playerid):new Player();
			$p->firstName = (isset($_POST["txtBxFirstName"]))?$_POST["txtBxFirstName"]:$p->firstName;
			$p->MI = (isset($_POST["MI"]))?$_POST["MI"]:$p->MI;
			$p->lastName = (isset($_POST["txtBxLastName"]))?$_POST["txtBxLastName"]:$p->lastName;
			$p->emailAddress = (isset($_POST["txtBxEmailAddr"]))?$_POST["txtBxEmailAddr"]:$p->emailAddress;
			
			if(isset($_POST["dobYear"]) && isset($_POST["dobMonth"]) && isset($_POST["dobDate"])){
				$p->dob = $_POST["dobYear"]."/".$_POST["dobMonth"]."/".$_POST["dobDate"];	
			}
			
			$p->bio = (isset($_POST["taBio"]))?$_POST["taBio"]:$p->bio;
			$p->currentCity = (isset($_POST["txtBxCurrentCity"]))?$_POST["txtBxCurrentCity"]:$p->currentCity;
			$p->homeTown = (isset($_POST["txtBxNativeTown"]))?$_POST["txtBxNativeTown"]:$p->homeTown; 
			$p->verified = isset($_POST["chkBxVerified"]);
			$p->locked = isset($_POST["chkBxLocked"]); 
			$p->admin = isset($_POST["chkBxIsAdmin"]);
			$this->model->updatePlayer($p);
			
			
			
			if(isset($_POST[AdminItemEnum::PLAYER_MGMT]) && $this->model->isAdmin) {
				header(sprintf("Location:?%s",AdminItemEnum::PLAYER_MGMT));
			}
			else{
	 			header(sprintf("Location:?viewProfile&playerid=%s",$playerid));
			}
	 	}
	 	else if(isset($_GET["viewProfile"]) || isset($_GET["editProfile"])){
	 		$this->model->selected = MenuItemEnum::PLAYERS;
	 		
	 		if(!isset($me) && isset($_SESSION["me"]))
				$me = $_SESSION["me"];
			
	 		$isEditable = (isset($me) && (($me->playerid == $playerid) || $me->admin));
	 		
	 		$player = $this->model->getPlayerById($playerid);
			$appearances = $this->model->getAppearance($playerid);
			$imageData = $this->model->getProfilePic($playerid);
			
			$noImage = (!(is_numeric($imageData->photoId)) || $imageData->photoId < 1);
			
			$standings = $this->model->getStandingByYear($playerid);
			
	 		if($playerid > -1){
	 			if(isset($_GET["viewProfile"]))
	 				$content = "view/view_profile.php";
	 			else if(isset($_GET["editProfile"]))
	 				$content = "view/edit_profile.php";
	 			else
	 				$content = "view/yearly_player_standing.php";
	 		}
	 		else
	 			$content = "view/yearly_player_standing.php";	
	 	}
	 	else if(isset($_GET["managePhotos"])){
	 		$this->model->selected = MenuItemEnum::PLAYERS;
	 		
	 		if(isset($_GET["playerid"]) && $_GET["playerid"] != "")
	 			$playerid = $_GET["playerid"];
	 		else if(!isset($me) && isset($_SESSION["me"]))
	 			$playerid = $_SESSION["me"]->playerid;
	 		
	 		$results = $this->model->getPhotosByPlayerId($playerid);
	 		
	 		if($playerid > -1){
	 			$content = "view/manage_photos.php";
	 		}
	 	}
	 	else if(isset($_GET[MenuItemEnum::YEARS])){
	 		$this->model->selected = MenuItemEnum::YEARS;
	 		$champList = $this->model->getChampions();
	 		$sureshotwinners = $this->model->getSureshotWinners();
	 		$content = "view/champion_list.php";
	 	}
	 	else if(isset($_GET[MenuItemEnum::PLAYERS])){
	 		$this->model->selected = MenuItemEnum::PLAYERS;
	 		$playerList = $this->model->searchPlayer(null,null,null,null,null,null,null,null,null);
	 		$content = "view/player_viewlist.php";
	 	}
	 	else if(isset($_GET["viewResultByYear"])){
	 		
	 		$this->model->selected = MenuItemEnum::YEARS;
	 		$event = (isset($_GET["eventid"]) && is_numeric($_GET["eventid"]))?$this->model->getEventById($_GET["eventid"]):$this->model->getLatestEvent();
	 		$resultRows = $this->model->getResultByYear($event->eventId);
	 		
	 		
	 		$content = "view/yearly_player_standing.php";
	 		
	 	}
	 	else if(isset($_GET[MenuItemEnum::COURSES])){
	 		$this->model->selected = MenuItemEnum::COURSES;
	 		if(isset($_GET["venueid"]) && is_numeric($_GET["venueid"])){
	 			$result = $this->model->getCourseListByVenueId($_GET["venueid"]);
	 			$content = "view/course_list.php";
	 		}
	 		else{
		 		$result = $this->model->getAllCourses();
		 		$content = "view/venue_list.php";
	 		}
	 	}
	 	/*
	 	 * Admin panel
	 	 */
	 	else if($this->model->isAdmin && $this->model->adminMode){
	 		
	 		//Player management
	 		if((isset($_GET[AdminItemEnum::PLAYER_MGMT]) || isset($_POST[AdminItemEnum::PLAYER_MGMT]))){
	 			$this->model->selected = AdminItemEnum::PLAYER_MGMT;
	 		
	 			if(isset($_GET["edit"])){
	 				$playerid = (isset($_GET["playerid"]) && trim($_GET["playerid"]) != "" && is_numeric($_GET["playerid"]))?$_GET["playerid"]:-1;
	 				$player = ($playerid !=-1)?$this->model->getPlayerById($playerid):new Player();
	 				$imageData = $this->model->getProfilePic($playerid);
	 				$noImage = (!(is_numeric($imageData->photoId)) || $imageData->photoId < 1);
	 				$content = "view/edit_profile.php";
	 			}
	 			else if(isset($_GET["create"])){
	 				$content = "view/edit_profile.php";
	 			}
	 			else{
	 		
	 				$result = PlayerMgmt::searchPlayer(null,null,null,null,null,null,null,null,null);
	 				$content = "view/admin/usermgmt_list.php";
	 			}
	 		}
	 		//Course management
	 		else if(isset($_GET[AdminItemEnum::COURSES])|| isset($_POST[AdminItemEnum::COURSES])){
	 			$this->model->selected = AdminItemEnum::COURSES;
	 			if(isset($_POST["btnSaveCourse"])){
	 				$course = CourseMgmt::getCourse($_POST["courseid"]);
	 				$course->coursename = $_POST["txtBxCourseName"];
	 				$course->venue = VenueMgmt::searchVenues($_POST["ddVenueList"], null, null)[0];
	 				$course->venue->venueid = $_POST["ddVenueList"];
	 				
	 				CourseMgmt::updateCourse($course);
	 				
	 				$distination = sprintf("Location: ?%s&edit&courseid=%s",AdminItemEnum::COURSES,$course->courseid);
	 				header($distination);
	 			}
	 			else if(isParamSet("editVenue") && isParamSet("venueid")){
	 				if(isset($_POST["btnSaveVenue"])){
	 					$venue = new Venue($_GET["venueid"], $_POST["txtBxVenueName"]);
	 					$venue->address1 = $_POST["txtBxAddress1"];
	 					$venue->address2 = $_POST["txtBxAddress2"];
	 					$venue->city = $_POST["txtBxCity"];
	 					$venue->statecode = $_POST["txtBxStateCode"];
	 					$venue->zipcode = $_POST["txtBxZipcode"];
	 					$venue->phone = $_POST["txtByPhone"];
	 					$venue->webaddress = $_POST["txtBxURL"];
	 					$venue->emailaddress = $_POST["txtEmailAddress"];
	 					$this->model->updateVenue($venue);
	 				}
	 				$venue = (isset($_GET["venueid"]))?$this->model->getVenue($_GET["venueid"]):null;
	 				
	 				$content = "view/admin/venue_edit.php";
	 				
	 			}
	 			else if((isset($_GET["editCourse"]) && isset($_GET["courseid"])) || (isset($_POST["editCourse"]) && isset($_POSTT["courseid"]))){
	 				$courseid = (isset($_GET["courseid"]) && is_numeric($_GET["courseid"]))?$_GET["courseid"]:((isset($_POST["courseid"]) && is_numeric($_POST["courseid"]))?$_POST["courseid"]:-1);
	 				$course = ($courseid != -1)?$this->model->getCourse($courseid):new Course();
	 				$venuelist = $this->model->getAllVenues();
	 				$holelist = $this->model->getHolesByCourseId($courseid);
	 				$content = "view/admin/course_edit.php";
	 			}
	 			else{
	 				$result = $this->model->searchCourses(null,null,0);
	 				$content = "view/admin/course_mgmt_list.php";
	 			}
	 		
	 		}
	 		//Data Import Wizard
	 		else if((isset($_GET[AdminItemEnum::RESULT_IMPORT])
	 				&& isset($_GET["step"])
	 				&& is_numeric($_GET["step"]))
	 				||
	 				(isset($_POST[AdminItemEnum::RESULT_IMPORT])
	 						&& isset($_POST["step"])
	 						&& is_numeric($_POST["step"]))
	 		){
	 			$step = (isset($_POST["step"]))?intval($_POST["step"]):intval($_GET["step"]);
	 		
	 			$this->model->inAdmin = true;
	 			$this->model->selected = AdminItemEnum::RESULT_IMPORT;
	 		
	 			$me = (isset($_SESSION["me"]))?$_SESSION["me"]:null;
	 		
	 			if($me == null)
	 				header(sprintf("Location:?%s",$this->model->selected));
	 				
	 			$oWizSteps = WizardSteps::getInstance();
	 			$oWizSteps->backToBeginning();
	 			$oWizSteps->setCurrentStep($step);
	 			$wizStepList = $oWizSteps->getList();
	 				
	 			$importStatusId = -1;
	 			if(
	 			(isset($_GET["import_status_id"]) && is_numeric($_GET["import_status_id"]))
	 			||
	 			(isset($_POST["import_status_id"]) && is_numeric($_POST["import_status_id"]))
	 			)
	 			{
	 				$importStatusId = (isset($_GET["import_status_id"]))?intval($_GET["import_status_id"]):intval($_POST["import_status_id"]);
	 			}
	 				
	 			switch($oWizSteps->getCurrentStep()){
	 				case 1:
	 					if(isset($_POST) && $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["iStatus2Rmv"])){
	 						foreach($_POST["iStatus2Rmv"] as $val){
	 							$this->model->deleteImportStatus($val);
	 						}
	 						header(sprintf("Location:?%s",$this->model->selected));
	 					}
	 						
	 					$statusList = $this->model->getImportStatus($me->playerid,null);
	 					break;
	 				case 2://File Upload
	 					if(isset($_POST["event_year"]) && isset($_FILES["srccsv"]["name"])){
	 						if(!(isset($_POST["event_year"]) && is_numeric($_POST["event_year"]))){
	 							echo "Event year is either missing or invalid value";
	 						}
	 						$targetPath = "tmp/";
	 		
	 						$success = false;
	 						$msg = "";
	 							
	 						$eventYear = $_POST["event_year"];
	 						try{
	 							$size = $_FILES["srccsv"]["size"];
	 								
	 							$imptStatus = new ImportStatus();
	 							$imptStatus->adminId = $me->playerid;
	 							$imptStatus->fileName = $_FILES["srccsv"]["name"];
	 								
	 							$importStatusId = $this->model->createImportStatus($imptStatus);
	 								
	 							$targetPath = $targetPath.basename($imptStatus->fileName);
	 								
	 							$success = (move_uploaded_file($_FILES["srccsv"]["tmp_name"],$targetPath));
	 								
	 							if($success){
	 								if($this->model->bulkInsert($targetPath,$eventYear,$importStatusId)){
	 									$this->model->fillInIds();
	 								}
	 							}
	 							else{
	 								$msg = "There was an error uploading the file, please try again.";
	 							}
	 						}
	 						catch(Exception $e){
	 							$msg = $e->getMessage();
	 							echo $msg;
	 						}
	 						if($success){
	 							header(sprintf("Location:?%s&step=3&import_status_id=%s",$this->model->selected,$importStatusId));
	 						}
	 					}
	 					break;
	 				case 3:
	 					if(isset($_POST["btnFindMatch"]) && $_POST["btnFindMatch"] != ""){
	 						$this->model->fillInIds();
	 						header(sprintf("Location:?%s&step=3&import_status_id=%s&msg=%s",$this->model->selected,$importStatusId,urlencode("IDs filled in")));
	 					}
	 					if(isset($_POST["btnInsertNew"]) && $_POST["btnInsertNew"] != ""){
	 						$this->model->insertNewPlayers();
	 						header(sprintf("Location:?%s&step=4&import_status_id=%s",$this->model->selected,$importStatusId));
	 					}
	 					$newPlayerList = $this->model->listNewPlayers($importStatusId);
	 					break;
	 				case 4:
	 					$result = $this->model->listNewCourses($importStatusId);
	 					break;
	 				case 5:
	 					$result = $this->model->displayContents($importStatusId);
	 					break;
	 				case 6:
	 					$this->model->importResults($importStatusId);
	 					break;
	 			}
	 				
	 			$wiz_title = "<h2>".$oWizSteps->printTitle()."</h2>";
	 			$wiz_banner = "view/admin/wiz_step_bars.inc.php"; 
	 			$content = "view/admin/".$oWizSteps->getCurrentFile();
	 		}
	 		else{
	 			$this->callHome();
	 		}
	 	}
	 	else if(isset($_GET["home"])){
	 		$this->callHome();
	 	}
	 	else{
	 		$this->callHome();	
	 	}
	 	
	 	include_once("view/portalframe.php");
 	}
 	
 	private function callHome(){
 		$event = $this->model->getLatestEvent();
 		$resultRows = ($event !=null)?$this->model->getResultByYear($event->eventId):null;
	 	$content = "view/yearly_player_standing.php";
	 	include_once("view/portalframe.php");
 	}
}
?>
